package dao

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"myblog/model"
)

type Manager interface {
	AddUser(user *model.User)
	FindUser(name string, pw string) model.User

	AddBlog(blog *model.Blog)
	FindAll(bl []model.Blog) []model.Blog

	FindBlog(id int) model.Blog
}

type manager struct {
	db *gorm.DB
}

var Mgr Manager

func init() {
	dsn := "root:123@tcp(8.130.52.55:3306)/golang_db?charset=utf8&parseTime=True&loc=Local"
	Db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	m := new(manager)
	m.db = Db
	Mgr = m
	err = Db.AutoMigrate(&model.User{})
	if err != nil {
		return
	}
	err = Db.AutoMigrate(&model.Blog{})
	if err != nil {
		return
	}

}

func (m manager) AddUser(user *model.User) {

	m.db.Create(user)
}

func (m manager) FindUser(name string, pw string) model.User {
	var u = model.User{}
	m.db.Where("username = ? AND password = ?", name, pw).Find(&u)
	return u
}

func (m manager) AddBlog(blog *model.Blog) {
	m.db.Create(blog)
}

func (m manager) FindAll(bl []model.Blog) []model.Blog {
	m.db.Find(&bl)
	return bl
}

func (m manager) FindBlog(id int) model.Blog {
	var b model.Blog
	m.db.Where("id = ?", id).First(&b)
	fmt.Println(b)
	return b
}
